package goroutinePool

import (
	"fmt"
	"sync"
)

type Pool struct {
	CandidateChan chan *Task
	WorkChan      chan *Task
	JobNum        int
	Wg            sync.WaitGroup
}

func NewPool(num int) *Pool {
	return &Pool{
		CandidateChan: make(chan *Task, num),
		WorkChan:      make(chan *Task),
		JobNum:        num,
	}
}

func (p *Pool) work() {
	for task := range p.WorkChan {
		fmt.Println(task.id, "开始工作")
		task.Excute()
		p.Wg.Done()
	}
}

func (p *Pool) Submit(t *Task) {
	fmt.Println(t.id, "进入协程")
	p.CandidateChan <- t
}

func (p *Pool) Run() {
	for i := 0; i < p.JobNum; i++ {
		// 会有jobNum个协程 在执行任务，任务来了就执行，没来就阻塞
		go p.work()
	}

	for task := range p.CandidateChan {
		p.WorkChan <- task
	}

}
